package com.beone.admin.controller.base;


import com.base.SuperController;
import com.beone.admin.annotation.Log;
import com.beone.admin.common.AdminConstants;
import com.beone.admin.entity.SysJob;
import com.beone.admin.exception.MvcException;
import com.beone.admin.quartz.JobTask;
import com.beone.admin.service.SysJobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

/**
 * @Title  前端控制器
 * @Author 覃球球
 * @Version 1.0 on 2018-10-25
 * @Copyright 贝旺科权
 */
@Api(value = "系统定时任务管理模块", tags = {"系统定时任务管理接口"})
@Controller
@RequestMapping("/system/job")
public class SysJobController extends SuperController {

    private static final Logger log = LoggerFactory.getLogger(SysJobController.class);

    @Autowired
    private SysJobService sysJobService;

    @Autowired
    private JobTask jobTask;

    /**
     * 任务管理 入口
     * @return
     */
    @RequestMapping("")
    public String index() throws MvcException{
        return "base/job/index";
    }

    /**
     * 任务管理 显示添加页面
     * @return
     */
    @GetMapping("/showAdd")
    public String showAdd()  throws MvcException{
        return "base/job/form";
    }

    /**
     * 任务管理 显示修改页面
     * @return
     */
    @GetMapping("/showUpdate/{id}")
    public String showUpdate(@PathVariable("id") String id, ModelMap model) throws MvcException{
        try {
            model.addAttribute("id", id);
            model.addAttribute("job", sysJobService.selectById(id));
        }catch (Exception e) {
            log.error("showUpdate 异常 e = {}", e);
            throw new MvcException(e.getMessage());
        }
        return "base/job/form";
    }

    /**
     * 任务管理分页列表 JSON
     * @param job
     * @param currPage
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "系统定时任务列表", notes = "系统定时任务列表分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", required = true
                    , paramType = "param", dataType = "int"),
            @ApiImplicitParam(name = "rows", value = "每页最大显示记录数", required = true
                    , paramType = "param", dataType = "int")
    })
    @RequestMapping(value = "/list", produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
            method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object showList(SysJob job,
            @RequestParam(value = "page", defaultValue = AdminConstants.DEFAULT_PAGE_NUM) int currPage,
            @RequestParam(value = "rows", defaultValue = AdminConstants.PAGE_SIZE) int pageSize) {
        return  sysJobService.getSysJobPagination(job, currPage, pageSize);
    }

    /**
     * 保存任务
     * @param job
     * @return
     */
    @ApiOperation(value = "保存定时任务", notes = "保存定时任务 主键属性为空新增,否则修改")
    @ApiImplicitParam(name = "job", value = "定时任务详细实体", required = true
            , paramType = "form", dataType = "object")
    @Log(desc = "定时任务", type = Log.LOG_TYPE.SAVE)
    @PostMapping(value = "/save", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Object save(SysJob job) {

        if(StringUtils.isNotBlank(job.getId())){ //更新Job时，先检测Job是否已存在
            if (jobTask.checkJob(job)) {
                return super.responseResult("fail", "已经启动任务无法更新,请停止后更新！");
            }
        }

        if(sysJobService.saveJob(job)){
            return super.responseResult("success", "成功！");
        }
        return super.responseResult("fail", "失败！");
    }

    /**
     * 删除任务
     * @param id
     * @return
     */
    @Log(desc = "删除定时任务", type = Log.LOG_TYPE.DEL)
    @ApiOperation(value = "删除定时任务", notes = "根据任务ID删除定时任务 ")
    @ApiImplicitParam(name = "id", value = "任务ID", required = true, paramType = "param", dataType = "string")
    @PostMapping(value = "/delete/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Object delete(@PathVariable("id") String id) {
        SysJob job = sysJobService.selectById(id);
        if(job == null){
            return super.responseResult("fail", "任务不存在！");
        }

        boolean flag = jobTask.checkJob(job);
        if ((flag && job.getStatus() == 0) || !flag && job.getStatus() == 1) {
            return super.responseResult("fail", "您任务表状态和web任务状态不一致,无法删除！");
        }
        if (flag) {
            return super.responseResult("fail", "该任务处于启动中，无法删除！");
        }

        if(sysJobService.deleteById(id)){
            return super.responseResult("success", "成功！");
        }
        return super.responseResult("fail", "失败！");
    }

    /**
     * 立即执行Job
     * @param id
     * @return
     */
    @Log(desc = "立即执行Job", type = Log.LOG_TYPE.START)
    @ApiOperation(value = "立即执行Job", notes = "根据任务ID，立即执行Job ")
    @ApiImplicitParam(name = "id", value = "任务ID", required = true, paramType = "param", dataType = "string")
    @PostMapping(value = "/runJob/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Object runNowJob(@PathVariable("id") String id) {
        SysJob job = sysJobService.selectById(id);
        if(job == null){
            return super.responseResult("fail", "任务不存在！");
        }

        boolean result = jobTask.runNow(job);
        if(result){
            return super.responseResult("success", "正在执行。。。");
        }
        return super.responseResult("fail", "手动执行任务失败！");
    }

    /**
     * 启动Job
     * @param id
     * @return
     */
    @Log(desc = "启动Job", type = Log.LOG_TYPE.START)
    @ApiOperation(value = "启动Job", notes = "根据任务ID，启动Job ")
    @ApiImplicitParam(name = "id", value = "任务ID", required = true, paramType = "param", dataType = "string")
    @PostMapping(value = "/startJob/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Object startJob(@PathVariable("id") String id) {
        SysJob job = sysJobService.selectById(id);
        if(job == null){
            return super.responseResult("fail", "任务不存在！");
        }

        jobTask.startJob(job);
        job.setStatus(1); //启动
        sysJobService.updateById(job);
        return super.responseResult("success", "启动成功！");
    }

    /**
     * 停止job
     * @param id
     * @return
     */
    @Log(desc = "启动Job", type = Log.LOG_TYPE.STOP)
    @ApiOperation(value = "停止job", notes = "根据任务ID，停止job ")
    @ApiImplicitParam(name = "id", value = "任务ID", required = true, paramType = "param", dataType = "string")
    @PostMapping(value = "/endJob/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Object endJob(@PathVariable("id") String id) {

        SysJob job = sysJobService.selectById(id);
        if(job == null){
            return super.responseResult("fail", "任务不存在！");
        }
        jobTask.remove(job);
        job.setStatus(0); //停止
        sysJobService.updateById(job);
        return super.responseResult("success", "停止成功！");
    }
}

